package com.example.kingdee.jstSync.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.example.kingdee.KingdeeCreate.dto.CreateInDto;
import com.example.kingdee.KingdeeCreate.impl.CreateSalBillImpl;
import com.example.kingdee.block.JuShuiTanBlock;
import com.example.kingdee.common.StringUtils;
import com.example.kingdee.dto.PurchaseSyncDto;
import com.example.kingdee.dto.SyncDto;
import com.example.kingdee.entity.JstPurchase;
import com.example.kingdee.entity.JstPurchaseIn;
import com.example.kingdee.entity.PurchaseInItems;
import com.example.kingdee.entity.SyncLog;
import com.example.kingdee.exception.ProcedureException;
import com.example.kingdee.jstSync.JstSyncAbstract;
import com.example.kingdee.jstSync.entity.JstResult;
import com.example.kingdee.kingdeeBridge.common.RequestResult;
import com.example.kingdee.kingdeeBridge.dto.BillWriteInDto;
import com.example.kingdee.kingdeeBridge.dto.PushDto;
import com.example.kingdee.kingdeeBridge.entity.SrcBillEntry;
import com.example.kingdee.kingdeeBridge.kingdeeAbs.FolderKingdee;
import com.example.kingdee.kingdeeBridge.kingdeeImpl.impl.ReceiveNoticeImpl;
import com.example.kingdee.mapper.TBxStMapper;
import com.example.kingdee.sqlTool.SqlTool;
import com.example.kingdee.sqlTool.sqltoolEnum.FormIdEnum;
import com.example.kingdee.util.JuShuiTanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 聚水潭采购入库同步实现类
 */
@Service
public class JstPurSyncInImpl extends JstSyncAbstract {

    @Autowired
    private JuShuiTanBlock juShuiTanBlock;
    @Autowired
    private ReceiveNoticeImpl receiveNotice;
    @Autowired
    private TBxStMapper tBxStMapper;

    @Override
    public int getOrderInfoPage(SyncDto syncDto, PurchaseSyncDto purchaseSyncDtoPage) {
        return JuShuiTanUtil.getOrderInfoPage(purchaseSyncDtoPage, FormIdEnum.purchaseIn, juShuiTanBlock.getAccessToken());
    }

    @Override
    public JstResult selectJstResult(SyncDto syncDto,  PurchaseSyncDto purchaseSyncDto) {
        JstResult jstResult = new JstResult();
        //制定查询状态
        List<String> status = new ArrayList<>();
        status.add("Confirmed");
        //先从聚水潭上查询单据信息
        purchaseSyncDto.setJstFormId(FormIdEnum.purchaseIn.name());
        purchaseSyncDto.setStatusList(status);
        String jstInfoStr = juShuiTanBlock.getJstInfo(purchaseSyncDto);
        //格式化单据
        List<JstPurchaseIn> jstPurchases = JSONArray.parseArray(jstInfoStr, JstPurchaseIn.class);
        jstResult.setJstPurchaseInList(jstPurchases);
        return jstResult;
    }

    @Override
    public void kingdeeSync(SyncDto syncDto, JstResult jstResult) {
        List<JstPurchaseIn> jstPurchaseInList = jstResult.getJstPurchaseInList();
        for (JstPurchaseIn jstPurchaseIn : jstPurchaseInList) {
            //采购单号
            String poIdStr = String.valueOf(jstPurchaseIn.getPoId());
            //采购入库单号
            String ioIdStr = String.valueOf(jstPurchaseIn.getIoId());
            //预约单号
            String mergeSoId = jstPurchaseIn.getMergeSoId();
            //判断是否有预约入库单号
            if (StringUtils.isEmpty(mergeSoId)){
                continue;
            }
            //根据预约入库单号查询外部单号
            List<PurchaseInItems> itemsList = jstPurchaseIn.getItems();
            for (PurchaseInItems purchaseInItem : itemsList) {
                String skuId = purchaseInItem.getSkuId();
                //判断是否同步过
                int count = tBxStMapper.isExistInstock(ioIdStr, skuId);
                if (count > 0){
                    continue;
                }
                //判断是否有对应采购单行id
                Long purOrderEntryId = tBxStMapper.selectPurOrderEntryId(poIdStr, skuId);
                if (purOrderEntryId == null){
                    continue;
                }
                //判断是否还有未入库的数量
                Double residueQty = tBxStMapper.selectPurOrderOutStock(poIdStr, skuId);
                if (residueQty == null || residueQty > 0){
                    PushDto pushDto = new PushDto();
                    pushDto.setSrcFormId(FormIdEnum.purchaseOrder);
                    pushDto.setTargetFormId(FormIdEnum.stkInStock);
                    //组合实现类和抽象类
                    FolderKingdee folderKingdee = new FolderKingdee(receiveNotice);
                    //按明细行id进行下推
                    pushDto.setEntryIds(purOrderEntryId.toString());

                    RequestResult pushDownResult = new RequestResult();
                    Map<String, String> targetInfo = new HashMap<>();
                    try {
                        //进行单据下推
                        pushDownResult = folderKingdee.pushDown(pushDto);
                        //查询目标单据信息
                        targetInfo = folderKingdee.selectTargetBillEntry(String.valueOf(pushDownResult.getId()));
                    }catch (Exception e){
                        SyncLog syncLog = new SyncLog();
                        syncLog.setJstBillno(ioIdStr);
                        syncLog.setSyncErrorMsg(pushDownResult.getMsg());
                        insertSyncLog(syncDto, syncLog, false);
                        e.printStackTrace();
                    }
                    //修改目标单据信息
                    BillWriteInDto billWriteInDto = new BillWriteInDto();
                    List<SrcBillEntry> srcBillEntryList = new ArrayList<>();
                    SrcBillEntry srcBillEntry = new SrcBillEntry();
                    srcBillEntry.setEntryId(purOrderEntryId.toString());
                    srcBillEntry.setQty(purchaseInItem.getQty());
                    srcBillEntry.setStockNumber("CK001");
                    srcBillEntry.setReserved1(ioIdStr);
                    srcBillEntryList.add(srcBillEntry);
                    billWriteInDto.setSrcBillEntryList(srcBillEntryList);
                    RequestResult requestResult = receiveNotice.updateTargetBillEntry(pushDownResult.getId(), billWriteInDto, targetInfo);
                    if (requestResult.getCode().equals("500")){
                        receiveNotice.deleteTargetBill(pushDownResult.getId());
                        SyncLog syncLog = new SyncLog();
                        syncLog.setJstBillno(ioIdStr);
                        syncLog.setSyncErrorMsg(requestResult.getMsg());
                        insertSyncLog(syncDto, syncLog, false);
                    }
                    //提交审核订单
                    try {
                        receiveNotice.auditTargetBill(requestResult.getNumber());
                    }catch (ProcedureException e){
                        folderKingdee.deleteTargetBill(String.valueOf(pushDownResult.getId()));
                        SyncLog syncLog = new SyncLog();
                        syncLog.setJstBillno(ioIdStr);
                        syncLog.setSyncErrorMsg(e.getMsg());
                        insertSyncLog(syncDto, syncLog, false);
                    }
                    //生成成功日志
                    SyncLog syncLog = new SyncLog();
                    syncLog.setJstBillno(ioIdStr);
                    syncLog.setKingdeeBillno(requestResult.getNumber());
                    syncLog.setObjectId(requestResult.getId());
                    insertSyncLog(syncDto, syncLog, true);
                }
            }
        }
    }

    @Override
    protected void insertSyncLog(SyncDto syncDto, SyncLog syncLog, boolean isSucceed) {
        syncLog.setSyncType("采购入库同步");
        syncLog.setSrcBill("聚水潭采购入库单");
        syncLog.setTarBill("金蝶采购入库单");
        syncLog.setSyncTime(SqlTool.getNowForString());
        syncLog.setSyncUser(syncDto.getUserName() == null ? "系统自动同步" : syncDto.getUserName());
        if (isSucceed){
            syncLog.setSyncResult("同步成功");
            syncLog.setSyncErrorMsg("无");
        }else {
            syncLog.setIsDispose("未处理");
            syncLog.setSyncResult("同步失败");
        }
        tBxStMapper.insertSyncLog(syncLog);
    }
}
